# -*- coding: utf-8 -*-
from django.db import models
from django.db.models import permalink
from datetime import datetime
from opengov.settings import *
from django.utils.feedgenerator import rfc3339_date
from django.template import loader, Context
import codecs


class AtomFeed():
	url = None
	title = None
	author_name = "opengov.se"
	author_email = None
	entries = []

	def updated(self):
		if len(self.entries) > 0:
			return rfc3339_date(self.entries[0].updated)
		else:
			return rfc3339_date(datetime.today())


class AtomEntry():

	entry_id = None
	url = None
	title = None
	updated = None
	published = None
	summary = None
	content = None
	author = None

	def to_entryxml(self):

		template = loader.get_template('atom_entry.xml')
		c = Context({ 'entry_id': self.entry_id, 'title': self.title,'author': self.author,'summary': self.summary,'updated': self.updated.isoformat() + "T12:00:00+01:00", 'published': self.published.isoformat() + "T12:00:00+01:00", 'content': self.content, 'url':self.url})

		return template.render(c)

	def to_str(self):
		return self.title




class Topic(models.Model):
	"""Används inte förän jag hittat någon bra metod för att extrahera ämnen ur en text."""
	name = models.CharField(max_length=255)
	slug = models.CharField(max_length=255, blank=True, null=True)
	description = models.TextField("Beskrivning", blank=True)

	def __unicode__(self):
		return self.name

	class Meta:
		verbose_name= u"Ämnesområde"
		verbose_name_plural = u"Ämnesområden"



class Departement(models.Model):
	name = models.CharField(max_length=255)
	homepage_url = models.URLField(verify_exists=False, blank=True, null=True)
	code = models.CharField(max_length=255, blank=True, null=True, unique=True)
	sou_slug = models.CharField(max_length=255, blank=True, null=True)

	def __unicode__(self):
		return self.name

	class Meta:
		verbose_name= u"Departement"
		verbose_name_plural = u"Departement"

	def get_ext_url(self):
		return self.homepage_url

	@models.permalink
	def get_absolute_url(self):
		return ('vwgovtrackdepartementsingle', None, { 'sou_slug': self.sou_slug})



class SFSReferens(models.Model):
	rubrik = models.TextField("Rubrik", blank=True)
	sfsnummer = models.CharField("SFS-nummer", max_length=255, unique=True)

	def url(self):
		return "http://lagen.nu/%s" % self.sfsnummer

	def __unicode__(self):
		return self.sfsnummer + " " + self.rubrik

	class Meta:
		verbose_name= u"SFS-referens"
		verbose_name_plural = u"SFS-referenser"

	def get_ext_url(self):
		return "https://lagen.nu/%s" % self.sfsnummer

	@models.permalink
	def get_absolute_url(self):
		return ('vwgovtracksfssingle', None, { 'sfsnummer': self.sfsnummer})




class CelexReferens(models.Model):
	rubrik = models.TextField("Rubrik", blank=True)
	celexnummer = models.CharField("Celexnummer", max_length=255, unique=True)

	def get_ext_url(self):
		return "http://eur-lex.europa.eu/LexUriServ/LexUriServ.do?uri=CELEX:%s:SV:NOT" % self.celexnummer

	def __unicode__(self):
		return self.celexnummer

	class Meta:
		verbose_name= u"EU-dokument"
		verbose_name_plural = u"EU-dokument"
		ordering = ['-celexnummer']

	@models.permalink
	def get_absolute_url(self):
		return ('vwgovtrackcelexsingle', None, { 'celexnummer': self.celexnummer})




class Kommittedirektiv(models.Model):
	rubrik = models.TextField("Rubrik", blank=False)
	sammanfattning = models.TextField("Sammanfattning", blank=True)
	url = models.URLField(verify_exists=False)
	dir_nr = models.CharField("Direktivnummer", max_length=255, unique=True)
	departement = models.ForeignKey(Departement, related_name='kommittedirektiv')
	regeringssammantrade = models.DateField("Datum regeringssammanträde")
	redovisas = models.DateField("Datum redovisning", blank=True, null=True)

	#referenser 
	tillagg_till_utredning = models.ForeignKey('Utredning', related_name='tillaggsdirektiv', blank=True, null=True)
	sfser = models.ManyToManyField(SFSReferens, related_name='kommittedirektiv', blank=True, null=True)
	propositioner = models.ManyToManyField('Proposition', related_name='kommittedirektiv', blank=True, null=True)
	eu_ratt = models.ManyToManyField(CelexReferens, related_name='kommittedirektiv', blank=True, null=True)
	topics = models.ManyToManyField(Topic, related_name='kommittedirektiv', blank=True, null=True)


	#meta
	created=models.DateTimeField("Skapad", auto_now_add=True, editable=False)
	updated=models.DateTimeField("Uppdaterad", auto_now=True, editable=False)

	def content_fragment_path(self):
		return GOVTRACK_DOCS + "/komdir/komdir-" + self.dir_nr.replace(":","-") + ".html"

	def content(self):
		content_fragment = u""
		f = codecs.open(self.content_fragment_path(), "r", "utf-8")
		content_fragment = f.read()
		f.close()
		return content_fragment

	def __unicode__(self):
		return self.rubrik

	def get_ext_url(self):
		return self.url

	@models.permalink
	def get_absolute_url(self):
		return ('vwgovtrackkomdirsingle', None, { 'dir_nr': self.dir_nr})

	def to_atomentry(self):
		entry = AtomEntry()
		entry.entry_id = self.get_absolute_url()
		entry.url = self.get_absolute_url()
		entry.title = self.dir_nr + " " + self.rubrik
		entry.updated = self.regeringssammantrade
		entry.published = self.regeringssammantrade
		entry.author = self.departement.name
		entry.content = self.content()
		return entry

	class Meta:
		verbose_name= u"Kommittédirektiv"
		verbose_name_plural = u"Kommittédirektiv"
		ordering = ['-regeringssammantrade']
		



class CrawlItem(models.Model):
	nummer = models.CharField("Nummer", max_length=255)
	klass = models.CharField("Typ", max_length=255)

	def __unicode__(self):
		return self.klass + " " + self.nummer


class Utredning(models.Model):
	rubrik = models.TextField("Rubrik", blank=False)
	nummer = models.CharField("Nummer", max_length=255, unique=True)
	url = models.URLField(verify_exists=False, blank=True, null=True)
	departement = models.ForeignKey(Departement, related_name='utredningar', blank=True, null=True)
	direktiv = models.ManyToManyField(Kommittedirektiv, related_name='utredning', blank=True, null=True)
	redovisas = models.DateField("Datum redovisning", blank=True, null=True)
	updated = models.DateField("Senast uppdaterad", blank=True, null=True)
	status = models.CharField("Status", max_length=1)

	def get_ext_url(self):
		return u"http://www.riksdagen.se/webbnav/?nid=3255&doktyp=komm&dok_id=B2_%s" % self.nummer.replace(" ","")

	def __unicode__(self):
		return self.nummer + " " + self.rubrik

	@models.permalink
	def get_absolute_url(self):
		return ('vwgovtrackutredningsingle', None, { 'departementskod': self.departement.code  ,'nummer': self.nummer.split(" ")[1]})

	def get_ical_url(self):
		return self.get_absolute_url()[0:-1] + ".ics"

	class Meta:
		verbose_name= u"Utredning"
		verbose_name_plural = u"Utredningar"
		ordering = ['-updated']


class Betankande(models.Model):
	rubrik = models.TextField("Rubrik", blank=False)
	nummer = models.CharField("Nummer", max_length=255, unique=True)
	url = models.URLField(verify_exists=False)
	utredning = models.ForeignKey(Utredning, related_name='betankanden')

	#utgiven = models.DateField("Utgiven", blank=True, null=True)


	def __unicode__(self):
		return self.nummer + " " + self.rubrik

	class Meta:
		verbose_name= u"Betänkande"
		verbose_name_plural = u"Betänkanden"
		ordering = ['-nummer']


class Dokument(models.Model):
	rubrik = models.TextField("Rubrik", blank=False)
	pdf_url = models.URLField(verify_exists=False)
	url = models.URLField(verify_exists=False)
	betankande = models.ForeignKey(Betankande, related_name='dokument', blank=False, null=False)

	def __unicode__(self):
		return self.nummer + " " + self.rubrik

	class Meta:
		verbose_name= u"Dokument"
		verbose_name_plural = u"Dokument"
		ordering = ['rubrik']


class Proposition(models.Model):
	rubrik = models.TextField("Rubrik", blank=False)
	nummer = models.CharField("Nummer", max_length=255, unique=True)
	url = models.URLField(verify_exists=False, blank=True, null=True)
	datum = models.DateField("Datum", blank=True, null=True)

	def __unicode__(self):
		return self.rubrik

	def get_ext_url(self):
		return u"http://www.riksdagen.se/webbnav/?nid=37&doktyp=prop&rm=%s&bet=%s" % (self.nummer.split(":")[0], self.nummer.split(":")[1])

	@models.permalink
	def get_absolute_url(self):
		return ('vwgovtrackpropsingle', None, { 'nummer': self.nummer})
